package cn.itcast.jdbc;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import cn.itcast.jdbc.domain.User;

public class ORMTest {
	
	public static void main(String[] args) throws IllegalArgumentException, SQLException, IllegalAccessException, InvocationTargetException {
		User user = getUser("select id as Id,name as Name,birthday as Birthday,money as Money from user where id=1");
		System.out.println(user);
	}
	
	static User getUser(String sql) throws SQLException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int count = rsmd.getColumnCount();
			String[] colNames = new String[count];
			for (int i = 1; i <= count; i++) {
				colNames[i-1] = rsmd.getColumnLabel(i);
			}
			
			User user = null;
			
			if (rs.next()) {
				user = new User();
				
				for (int i = 0; i < colNames.length; i++) {
					String colName = colNames[i];
					String methodName = "set" + colName;
					System.out.println(methodName);
					Method[] ms = user.getClass().getMethods();
					for (Method m : ms) {
						if (methodName.equals(m.getName())) {
							m.invoke(user, rs.getObject(colName));
						}
					}
				}
			}
			return user;
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}

}
